js
// 请求拦截.js
(() => {
const rqwFetch = globalThis.fetch;
globalThis.fetch = async (...arg) => {
const [url, init] = arg;
const payload = JSON.parse(init.body);
if (
url.toString().endsWith("/api") &&
payload.channel === "prisma" &&
payload.action === "clientRequest"
) {
return rqwFetch("https://shenzilong.cn/studio_server/api", init);
} else {
return rqwFetch(...arg);
}
};
})();
ts
app.post(api_path, async (c) => {
const req = await c.req.json();
const [payload, resHelper] = reqParser(req);
const r = await execClientRequest(payload.data)
return c.json(resHelper(r, null));
});
interface queries {
schemaHash: string;
modelName: "Proxy_api";
operation: "count";
args?: {
take: 100;
skip: 0;
select: { id: true; Wallet_id: true; Wallet: true; createdAt: true; updatedAt: true };
};
}
interface payload {
data:
| {
schemaHash: string;
operation: "$transaction";
queries: queries[];
}
| queries;
}
async function execClientRequest(op: payload["data"]) {
if (op.operation == "$transaction") {
const { queries } = op;
const actions = queries.map(execQueries);
const r = await prisma.$transaction(actions);
return r;
} else if (["findMany", "count", "update"].includes(op.operation)) {
return execQueries(op);
}
function execQueries(op: queries) {
return prisma[toLowerCase(op.modelName) as /** 类型欺骗 */ "wallet"][op.operation](op.args);
}
}
function toLowerCase(str: string): string {
return str.toLowerCase();
}
function reqParser(req: any) {
const { requestId, action, payload } = req;
return [
payload as payload,
(data: any, error: any) => {
return {
requestId,
channel: "-prisma",
action,
payload: { error, data },
};
},
] as const;
}